'use strict';

var http = require('http');

var options = {
  host: 'httpbin.org',
  path: '/post',
  method: 'POST',
  headers: {}
};

function postState(state) {
  options.headers['Content-Length'] = state.length;
  var req = http.request(options, function (res) {
    res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  });

  req.write(state);
  req.end();
}

function changeColor() {
  temperHumidity.getTemperature(function (error, temperature) {
    if (error) {
      console.error(error);
      return;
    }
    lcd.print("temperature:"+temperature);
    console.log('temperature', temperature);
  });

  temperHumidity.getRelativeHumidity(function (error, humidity) {
    if (error) {
      console.error(error);
      return;
    }
    lcd.print("humidity:"+humidity);
    console.log('humidity', humidity);
  });

  var num1 = getRandom(0, 1);
  var num2 = getRandom(0, 1);
  var num3 = getRandom(0, 1);
  console.log(num1, num2, num3);
  $('#LedLight').setRGB([num1, num2, num3]);
}

function getRandom(min, max) {
  var r = Math.random() * (max - min);
  var re = r + min;
  re = Math.max(Math.min(re, max), min)

  return re;
}

var isLedOn = false;
var changeInterval=null;
var temperHumidity,lcd,sound,button,ledLight;
$.ready(function (error) {
  if (error) {
    console.log(error);
    return;
  }
  $('#SoundSensor').on('sound', function() {
    console.log('sound detected');
  });
   button= $('#button');
   sound=$('#Sound');
   lcd=$('#Lcd');
   ledLight= $('#LedLight');
  temperHumidity= $("#TemperHumidity");
  button.on('push', function () {
    console.log('Button pushed.');
    if (isLedOn) {

      changeInterval=setInterval(changeColor, 3000);
      sound.turnOn();


      ledLight.turnOn(function () {
        postState('turn on');
      });
    }else {
      lcd.clear();
      ledLight.turnOff();
      clearInterval(changeInterval);
      sound.turnOff();
    }

  });

  button.on('release', function () {
    console.log('Button released.');
    isLedOn = !isLedOn;
  });
});

$.end(function () {
  $('#led-r').turnOff();
});